package com.qf.base.util;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.base.util
 * @Description: 图片与Base64的转化问题
 * @Date 2022/8/3 14:01
 */
public class Base64Util {
    /**
     * 图片转base64
     */
    public static String image2Base64(BufferedImage image){
        //BufferedImage 是什么?
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try {
            ImageIO.write(image,"jpg",stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //内存流的数据变成字节数组
        byte[] bytes = stream.toByteArray();
        //字节数组转化为base64
        return Base64.encodeBase64String(bytes);
    }

    /**
     * base64转图片
     */
    public static BufferedImage base64ToImage(String base64){
        //入参为空直接return null
        if (StringUtils.isEmpty(base64)){
            return null;
        }

        //进行解码, 拿到字节数组
        byte[] bytes = Base64.decodeBase64(base64);
        //字节数组转BufferedImage
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        try {
            return ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception{

        String s = image2Base64(ImageIO.read(new File("D:\\9.jpg")));

        BufferedImage image = base64ToImage(s);
        //图片转base64
        String base64 = image2Base64(image);
        System.out.println(base64);
//        BufferedImage bufferedImage = base64ToImage(base64);
//        ImageIO.write(bufferedImage,"jpg",new File("D:\\昨日黄花1.jpg"));

    }

}
